package com.loanapp.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.loanapp.domain.CreditHistoryBean;
import com.loanapp.domain.LoanApplication;

public class CreditProcessService {

	private static Log log = LogFactory.getLog(CreditProcessService.class);

	private MessageSenderCreditProcess messageSender = null;

	private MessageReceiverCreditProcess messageReceiver = null;

	public MessageSenderCreditProcess getMessageSender() {
		return this.messageSender;
	}

	public void setMessageSender(MessageSenderCreditProcess messageSender) {
		this.messageSender = messageSender;
	}

	public MessageReceiverCreditProcess getMessageReceiver() {
		return this.messageReceiver;
	}

	public void setMessageReceiver(MessageReceiverCreditProcess messageReceiver) {
		this.messageReceiver = messageReceiver;
	}

	public void processCreditRequest() {
		log.debug("processCreditRequest called.");

		// First get the loan details from the queue
		LoanApplication loanApp = messageReceiver.receive();

		// Create credit history bean based on the results
		CreditHistoryBean creditHistory = new CreditHistoryBean();
		creditHistory.setLoanAppId(loanApp.getLoanAppId());
		creditHistory.setLoanAmount(loanApp.getLoanAmount());
		creditHistory.setLoanApproved(false);

		// In a real world application, the following logic should be
		// stored in an XML file or better in a Rules Engine so the credit
		// processing
		// logic would be easier to modify and maintain.

		// Set the Credit History flag
		if (loanApp.getCreditScore() > 499 && loanApp.getCreditScore() < 580) {
			creditHistory.setCreditHistory("BAD");
		} else if (loanApp.getCreditScore() > 579
				&& loanApp.getCreditScore() < 620) {
			creditHistory.setCreditHistory("LOW");
		} else if (loanApp.getCreditScore() > 619
				&& loanApp.getCreditScore() < 680) {
			creditHistory.setCreditHistory("OK");
		} else if (loanApp.getCreditScore() > 679
				&& loanApp.getCreditScore() < 700) {
			creditHistory.setCreditHistory("GOOD");
		} else if (loanApp.getCreditScore() > 699) {
			creditHistory.setCreditHistory("VERY_GOOD");
		}

		if (loanApp.getLoanAmount().doubleValue() <= 500000) {
			if (creditHistory.getCreditHistory().equals("VERY_GOOD")
					|| creditHistory.getCreditHistory().equals("GOOD")) {
				creditHistory.setLoanApproved(true);
			}
		} else if (loanApp.getLoanAmount().doubleValue() > 500000) {
			if (creditHistory.getCreditHistory().equals("VERY_GOOD")) {
				creditHistory.setLoanApproved(true);
			}
		}

		messageSender.send(creditHistory);

		log.debug("Done sending the loan details to credit request.");
	}
}
